<?php
namespace app\client\controller;
use app\client\lib\Redis;

class User extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function userInfo() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $params = request()->post();
        if(empty($params)){
            return errorResult('a');
        }
        
        $appId = config('config.wx.appid');
        
        $userModel = model('User');
        
        $user = $userModel->findOne(['user_id' => $this->userid], ['nickname', 'avatar', 'sex', 'unionid', 'session_key']);
        
        if($params['signature'] !== sha1($params['rawData'] . $user['session_key'])){ //验证不通过
            return errorResult('b');
        }
        
        
        $pc = new \app\client\lib\WXBizDataCrypt\WXBizDataCrypt($appId, $user['session_key']);
        
        $errCode = $pc->decryptData($params['encryptedData'], $params['iv'], $userInfo);
        
        if($errCode == 0) {
            $userInfo = json_decode($userInfo, true);
            $updateData = [];
            
            if($user['nickname'] !== $userInfo['nickName']){
                $updateData['nickname'] = $userInfo['nickName'];
            }
            
            if($user['avatar'] !== $userInfo['avatarUrl']){
                $updateData['avatar'] = $userInfo['avatarUrl'];
            }
            
            if($user['sex'] !== $userInfo['gender']){
                $updateData['sex'] = $userInfo['gender'];
            }
            
            if(empty($user['unionid']) && !empty($userInfo['unionId'])){ //还没有保存unionid
                $updateData['unionid'] = $userInfo['unionId'];
            }
            
            try {
                $redis = new Redis();
                $redis->set('user_' . $this->userid, ['nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl'], 'user_id' => $this->userid]);
                $redis->close();
            } catch (\Exception $e) {
                $redis->close();
            }
            
            $userModel->modify(['user_id' => $this->userid], $updateData);
            
            return successResult();
            
        }else{
            return errorResult('c');
        }
        
        
        
    }
    
}